// 故事接龙生成器主要逻辑
class StoryChain {
    constructor(achievementsSystem = null) {
        this.story = [];
        this.currentTurn = 'user'; // 'user' 或 'ai'
        this.turnCount = 0;
        this.startTime = null;
        this.isGenerating = false;
        this.achievementsSystem = achievementsSystem;
        
        // AI配置
        this.aiConfig = {
            maxTokens: 200,
            temperature: 0.8,
            creativePrompts: [
                "接下来发生了什么奇妙的事情？",
                "突然，一个意想不到的人物出现了...",
                "这时候，魔法开始发挥作用了...",
                "他们决定去一个神秘的地方冒险...",
                "一件奇怪的物品引起了他们的注意...",
                "天空中出现了不可思议的景象...",
                "这时，他们听到了一个神秘的声音...",
                "突然之间，一切都发生了变化..."
            ]
        };
        
        // 故事模板（用于本地模式）
        this.storyTemplates = {
            adventure: [
                "勇敢的主人公踏上了未知的旅程，面前是一片神秘的森林。",
                "森林深处传来奇怪的声音，树木仿佛在低语着古老的秘密。",
                "突然，一只会说话的动物从树后跳了出来，说要带他们去看神奇的东西。",
                "他们来到了一个隐藏的山洞，洞里闪烁着奇异的光芒。",
                "山洞里面藏着一个古老的宝藏，还有一张通往更神奇世界的地图。"
            ],
            fantasy: [
                "魔法学院的钟声敲响了，今天是年度魔法大赛的日子。",
                "主角发现自己的魔法天赋与众不同，能够与动物进行心灵沟通。",
                "一位神秘的教授告诉他，他其实是预言中的天选之人。",
                "在图书馆的禁书区，他找到了一本会自己翻页的魔法书。",
                "书中的文字化作光点飞出，组成了一扇通往魔法世界的大门。"
            ],
            scifi: [
                "2150年，人类收到了来自外太空的神秘信号。",
                "信号解码后显示，在银河系的边缘有一个适合人类居住的星球。",
                "主角作为志愿者的孩子，登上了前往新世界的星际飞船。",
                "飞船在航行途中遇到了一个巨大的太空生物，它似乎想传达什么信息。",
                "通过心灵感应装置，主角发现这个生物是在警告他们前方的危险。"
            ]
        };
        
        this.initializeElements();
        this.bindEvents();
        this.loadFromStorage();
        this.startTimer();
    }
    
    // 初始化DOM元素
    initializeElements() {
        // 输入元素
        this.userInput = document.getElementById('userInput');
        this.continueInput = document.getElementById('continueInput');
        
        // 按钮元素
        this.startBtn = document.getElementById('startBtn');
        this.regenerateBtn = document.getElementById('regenerateBtn');
        this.continueBtn = document.getElementById('continueBtn');
        this.submitContinueBtn = document.getElementById('submitContinueBtn');
        this.saveBtn = document.getElementById('saveBtn');
        this.loadBtn = document.getElementById('loadBtn');
        this.newStoryBtn = document.getElementById('newStoryBtn');
        this.downloadBtn = document.getElementById('downloadBtn');
        this.shareBtn = document.getElementById('shareBtn');
        
        // 显示元素
        this.storyContainer = document.getElementById('storyContainer');
        this.userInputSection = document.getElementById('userInputSection');
        this.aiResponseSection = document.getElementById('aiResponseSection');
        this.continueSection = document.getElementById('continueSection');
        this.thinkingIndicator = document.getElementById('thinkingIndicator');
        this.aiResponse = document.getElementById('aiResponse');
        this.responseContent = document.getElementById('responseContent');
        
        // 统计元素
        this.storyLengthEl = document.getElementById('storyLength');
        this.turnCountEl = document.getElementById('turnCount');
        this.timeElapsedEl = document.getElementById('timeElapsed');
        
        // 模态框元素
        this.modal = document.getElementById('messageModal');
        this.modalTitle = document.getElementById('modalTitle');
        this.modalBody = document.getElementById('modalBody');
        this.modalClose = document.getElementById('modalClose');
        this.modalConfirm = document.getElementById('modalConfirm');
        
        // 字数统计元素
        this.charCounts = document.querySelectorAll('.char-count');
    }
    
    // 绑定事件监听器
    bindEvents() {
        // 输入事件
        this.userInput.addEventListener('input', () => this.handleInputChange(this.userInput, 0));
        this.continueInput.addEventListener('input', () => this.handleInputChange(this.continueInput, 1));
        
        // 按钮事件
        this.startBtn.addEventListener('click', () => this.startStory());
        this.regenerateBtn.addEventListener('click', () => this.regenerateResponse());
        this.continueBtn.addEventListener('click', () => this.showContinueInput());
        this.submitContinueBtn.addEventListener('click', () => this.submitContinue());
        
        // 工具栏事件
        this.saveBtn.addEventListener('click', () => this.saveStory());
        this.loadBtn.addEventListener('click', () => this.loadStory());
        this.newStoryBtn.addEventListener('click', () => this.newStory());
        this.downloadBtn.addEventListener('click', () => this.downloadStory());
        this.shareBtn.addEventListener('click', () => this.shareStory());
        
        // 模态框事件
        this.modalClose.addEventListener('click', () => this.hideModal());
        this.modalConfirm.addEventListener('click', () => this.hideModal());
        this.modal.addEventListener('click', (e) => {
            if (e.target === this.modal) this.hideModal();
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch(e.key) {
                    case 's':
                        e.preventDefault();
                        this.saveStory();
                        break;
                    case 'n':
                        e.preventDefault();
                        this.newStory();
                        break;
                    case 'Enter':
                        if (this.currentTurn === 'user' && !this.startBtn.disabled) {
                            e.preventDefault();
                            this.startStory();
                        }
                        break;
                }
            }
        });
    }
    
    // 处理输入变化
    handleInputChange(textarea, index) {
        const text = textarea.value.trim();
        const charCount = textarea.value.length;
        const charCountEl = this.charCounts[index];
        
        // 更新字符计数
        charCountEl.textContent = `${charCount}/500`;
        
        // 更新字符计数颜色
        if (charCount > 450) {
            charCountEl.style.color = 'var(--error-color)';
        } else if (charCount > 400) {
            charCountEl.style.color = 'var(--warning-color)';
        } else {
            charCountEl.style.color = 'var(--text-muted)';
        }
        
        // 启用/禁用按钮
        if (index === 0) {
            this.startBtn.disabled = text.length < 10;
        } else {
            this.submitContinueBtn.disabled = text.length < 10;
        }
    }
    
    // 开始故事
    async startStory() {
        const userInput = this.userInput.value.trim();
        
        if (userInput.length < 10) {
            this.showMessage('提示', '请输入至少10个字符作为故事开头哦！');
            return;
        }
        
        // 添加用户输入到故事
        this.addToStory('user', userInput);
        this.currentTurn = 'ai';
        this.turnCount++;
        
        // 更新成就系统
        if (this.achievementsSystem) {
            const newUnlocks = this.achievementsSystem.updateStats('story_word', userInput.length);
            if (newUnlocks.length > 0) {
                setTimeout(() => {
                    newUnlocks.forEach(achievement => {
                        this.achievementsSystem.showAchievementNotification(achievement);
                    });
                }, 1000);
            }
        }
        
        // 更新界面
        this.userInputSection.style.display = 'none';
        this.aiResponseSection.style.display = 'block';
        this.showThinking();
        
        // 生成AI响应
        await this.generateAIResponse(userInput);
        
        // 更新统计
        this.updateStats();
    }
    
    // 添加内容到故事
    addToStory(speaker, content) {
        this.story.push({
            speaker: speaker,
            content: content,
            timestamp: new Date().toISOString()
        });
        
        this.renderStory();
    }
    
    // 渲染故事内容
    renderStory() {
        const storyHTML = this.story.map((item, index) => {
            const speakerClass = item.speaker === 'user' ? 'user-part' : 'ai-part';
            const speakerIcon = item.speaker === 'user' ? '👶' : '🤖';
            const speakerLabel = item.speaker === 'user' ? '小朋友说' : 'AI助手说';
            
            return `
                <div class="story-segment ${speakerClass}">
                    <div class="segment-header">
                        <span class="speaker-icon">${speakerIcon}</span>
                        <span class="speaker-label">${speakerLabel}</span>
                        <span class="segment-number">第${Math.floor(index / 2) + 1}轮</span>
                    </div>
                    <div class="segment-content">${this.escapeHtml(item.content)}</div>
                </div>
            `;
        }).join('');
        
        this.storyContainer.innerHTML = storyHTML;
        
        // 滚动到最新内容
        this.storyContainer.scrollTop = this.storyContainer.scrollHeight;
    }
    
    // 显示思考指示器
    showThinking() {
        this.thinkingIndicator.style.display = 'flex';
        this.aiResponse.style.display = 'none';
        this.isGenerating = true;
    }
    
    // 隐藏思考指示器
    hideThinking() {
        this.thinkingIndicator.style.display = 'none';
        this.aiResponse.style.display = 'block';
        this.isGenerating = false;
    }
    
    // 生成AI响应
    async generateAIResponse(userContent) {
        try {
            // 模拟AI思考时间
            await this.delay(2000);
            
            // 获取AI回复内容
            const aiResponse = this.getLocalAIResponse(userContent);
            
            // 添加到故事
            this.addToStory('ai', aiResponse);
            
            // 显示响应
            this.responseContent.textContent = aiResponse;
            this.hideThinking();
            
            // 保存到本地存储
            this.saveToStorage();
            
        } catch (error) {
            console.error('生成AI响应失败:', error);
            this.showMessage('错误', 'AI生成故事时遇到了问题，请稍后再试。');
            this.hideThinking();
        }
    }
    
    // 本地AI响应生成（模拟）
    getLocalAIResponse(userContent) {
        // 分析用户输入的关键词
        const keywords = this.extractKeywords(userContent);
        
        // 选择合适的故事模板
        let templates = [];
        if (keywords.some(k => ['森林', '冒险', '旅程', '寻找'].includes(k))) {
            templates = this.storyTemplates.adventure;
        } else if (keywords.some(k => ['魔法', '学校', '神奇', '咒语'].includes(k))) {
            templates = this.storyTemplates.fantasy;
        } else if (keywords.some(k => ['太空', '外星', '未来', '科技'].includes(k))) {
            templates = this.storyTemplates.scifi;
        }
        
        // 如果没有匹配的模板，使用通用响应
        if (templates.length === 0) {
            templates = [
                "这个开头真有趣！接下来，故事的主角遇到了一个神秘的陌生人，",
                "哇，真是个精彩的开头！突然之间，周围的环境发生了奇妙的变化，",
                "太棒了！就在这个时候，一个意想不到的机会出现在了主角面前，",
                "有意思！这时，远处传来了奇怪的声音，吸引了所有人的注意，",
                "精彩的开头！突然，天空中出现了一道绚丽的彩虹，好像在指引着什么方向..."
            ];
        }
        
        // 随机选择一个响应并添加创意元素
        const baseResponse = templates[Math.floor(Math.random() * templates.length)];
        const creativeElement = this.aiConfig.creativePrompts[Math.floor(Math.random() * this.aiConfig.creativePrompts.length)];
        
        return `${baseResponse} ${creativeElement}`;
    }
    
    // 提取关键词
    extractKeywords(text) {
        const keywords = ['猫咪', '学校', '魔法', '森林', '冒险', '太空', '外星', '神奇', '神秘', '未来', '科技', '咒语', '旅程', '寻找'];
        return keywords.filter(keyword => text.includes(keyword));
    }
    
    // 重新生成AI响应
    async regenerateResponse() {
        if (this.isGenerating) return;
        
        const lastUserContent = this.story.filter(item => item.speaker === 'user').pop();
        if (!lastUserContent) return;
        
        // 移除最后一个AI响应
        if (this.story.length > 0 && this.story[this.story.length - 1].speaker === 'ai') {
            this.story.pop();
        }
        
        this.showThinking();
        await this.generateAIResponse(lastUserContent.content);
    }
    
    // 显示继续输入区域
    showContinueInput() {
        this.aiResponseSection.style.display = 'none';
        this.continueSection.style.display = 'block';
        this.continueInput.focus();
        this.currentTurn = 'user';
    }
    
    // 提交继续内容
    async submitContinue() {
        const continueContent = this.continueInput.value.trim();
        
        if (continueContent.length < 10) {
            this.showMessage('提示', '请输入至少10个字符来继续故事哦！');
            return;
        }
        
        // 添加用户内容
        this.addToStory('user', continueContent);
        this.turnCount++;
        
        // 清空输入
        this.continueInput.value = '';
        this.submitContinueBtn.disabled = true;
        
        // 切换到AI响应
        this.currentTurn = 'ai';
        this.continueSection.style.display = 'none';
        this.aiResponseSection.style.display = 'block';
        this.showThinking();
        
        // 生成AI响应
        await this.generateAIResponse(continueContent);
        
        // 更新统计
        this.updateStats();
    }
    
    // 保存故事到本地存储
    saveToStorage() {
        const data = {
            story: this.story,
            turnCount: this.turnCount,
            startTime: this.startTime,
            lastSaved: new Date().toISOString()
        };
        
        localStorage.setItem('storyChain_current', JSON.stringify(data));
        localStorage.setItem('storyChain_list', JSON.stringify(this.getSavedStoriesList()));
    }
    
    // 从本地存储加载
    loadFromStorage() {
        const savedData = localStorage.getItem('storyChain_current');
        if (savedData) {
            try {
                const data = JSON.parse(savedData);
                this.story = data.story || [];
                this.turnCount = data.turnCount || 0;
                this.startTime = data.startTime;
                
                if (this.story.length > 0) {
                    this.renderStory();
                    this.updateStats();
                    
                    // 如果故事有内容，显示继续界面
                    if (this.story.length > 0 && this.story[this.story.length - 1].speaker === 'ai') {
                        this.userInputSection.style.display = 'none';
                        this.showContinueInput();
                    }
                }
            } catch (error) {
                console.error('加载保存的故事失败:', error);
            }
        }
    }
    
    // 保存故事
    saveStory() {
        if (this.story.length === 0) {
            this.showMessage('提示', '还没有开始创作故事哦！');
            return;
        }
        
        const storyTitle = prompt('请为这个故事起个名字：', `故事_${new Date().toLocaleDateString()}`);
        if (!storyTitle) return;
        
        const savedStories = JSON.parse(localStorage.getItem('storyChain_saved') || '{}');
        savedStories[storyTitle] = {
            story: this.story,
            turnCount: this.turnCount,
            startTime: this.startTime,
            savedAt: new Date().toISOString(),
            title: storyTitle
        };
        
        localStorage.setItem('storyChain_saved', JSON.stringify(savedStories));
        this.showMessage('成功', `故事"${storyTitle}"已保存成功！`);
    }
    
    // 加载故事
    loadStory() {
        const savedStories = JSON.parse(localStorage.getItem('storyChain_saved') || '{}');
        const storyTitles = Object.keys(savedStories);
        
        if (storyTitles.length === 0) {
            this.showMessage('提示', '还没有保存的故事哦！');
            return;
        }
        
        // 创建选择列表
        const storyList = storyTitles.map(title => 
            `<option value="${title}">${title} (${savedStories[title].turnCount}轮)</option>`
        ).join('');
        
        const modalContent = `
            <div class="story-selector">
                <label for="storySelect">选择要加载的故事：</label>
                <select id="storySelect" class="story-select">
                    ${storyList}
                </select>
                <div class="story-actions">
                    <button class="btn btn-secondary" id="loadSelectedBtn">加载</button>
                    <button class="btn btn-danger" id="deleteSelectedBtn">删除</button>
                </div>
            </div>
        `;
        
        this.showModal('加载故事', modalContent);
        
        // 绑定选择器事件
        setTimeout(() => {
            const loadBtn = document.getElementById('loadSelectedBtn');
            const deleteBtn = document.getElementById('deleteSelectedBtn');
            const select = document.getElementById('storySelect');
            
            if (loadBtn) {
                loadBtn.addEventListener('click', () => {
                    const selectedTitle = select.value;
                    const storyData = savedStories[selectedTitle];
                    
                    this.story = storyData.story;
                    this.turnCount = storyData.turnCount;
                    this.startTime = storyData.startTime;
                    
                    this.renderStory();
                    this.updateStats();
                    this.saveToStorage();
                    
                    // 显示适当的界面
                    this.userInputSection.style.display = 'none';
                    if (this.story[this.story.length - 1].speaker === 'ai') {
                        this.showContinueInput();
                    } else {
                        this.aiResponseSection.style.display = 'block';
                        this.hideThinking();
                    }
                    
                    this.hideModal();
                    this.showMessage('成功', `故事"${selectedTitle}"加载成功！`);
                });
            }
            
            if (deleteBtn) {
                deleteBtn.addEventListener('click', () => {
                    const selectedTitle = select.value;
                    if (confirm(`确定要删除故事"${selectedTitle}"吗？`)) {
                        delete savedStories[selectedTitle];
                        localStorage.setItem('storyChain_saved', JSON.stringify(savedStories));
                        
                        // 更新选择列表
                        const remainingStories = Object.keys(savedStories);
                        if (remainingStories.length === 0) {
                            this.hideModal();
                            this.showMessage('提示', '已删除所有保存的故事');
                        } else {
                            select.innerHTML = remainingStories.map(title => 
                                `<option value="${title}">${title} (${savedStories[title].turnCount}轮)</option>`
                            ).join('');
                        }
                    }
                });
            }
        }, 100);
    }
    
    // 新建故事
    newStory() {
        if (this.story.length > 0) {
            if (!confirm('确定要开始新故事吗？当前的故事进度将会丢失。')) {
                return;
            }
        }
        
        this.story = [];
        this.turnCount = 0;
        this.startTime = new Date().toISOString();
        this.currentTurn = 'user';
        
        this.storyContainer.innerHTML = `
            <div class="story-placeholder">
                <div class="magic-wand">✨</div>
                <h2>准备好开始你的故事了吗？</h2>
                <p>在下方输入一个精彩的开头，让AI和你一起创造神奇的故事世界！</p>
            </div>
        `;
        
        this.userInputSection.style.display = 'block';
        this.aiResponseSection.style.display = 'none';
        this.continueSection.style.display = 'none';
        this.userInput.value = '';
        this.continueInput.value = '';
        this.startBtn.disabled = true;
        this.submitContinueBtn.disabled = true;
        
        this.updateStats();
        localStorage.removeItem('storyChain_current');
        
        this.showMessage('成功', '新的故事开始了！快输入你的精彩开头吧！');
    }
    
    // 下载故事
    downloadStory() {
        if (this.story.length === 0) {
            this.showMessage('提示', '还没有开始创作故事哦！');
            return;
        }
        
        const storyText = this.generateStoryText();
        const blob = new Blob([storyText], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        
        const link = document.createElement('a');
        link.href = url;
        link.download = `故事接龙_${new Date().toLocaleDateString()}.txt`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        
        this.showMessage('成功', '故事已下载到本地！');
    }
    
    // 分享故事
    shareStory() {
        if (this.story.length === 0) {
            this.showMessage('提示', '还没有开始创作故事哦！');
            return;
        }
        
        const storyText = this.generateStoryText();
        
        if (navigator.share) {
            navigator.share({
                title: '我的故事接龙作品',
                text: storyText.substring(0, 200) + '...',
            }).then(() => {
                this.showMessage('成功', '故事分享成功！');
            }).catch(() => {
                this.copyToClipboard(storyText);
            });
        } else {
            this.copyToClipboard(storyText);
        }
    }
    
    // 生成完整故事文本
    generateStoryText() {
        const title = `故事接龙作品\n${'='.repeat(50)}\n\n`;
        const stats = `创作统计：\n- 故事字数：${this.getTotalWordCount()}字\n- 接龙轮次：${this.turnCount}轮\n- 创作时间：${this.getElapsedTime()}\n\n${'='.repeat(50)}\n\n`;
        
        const content = this.story.map((item, index) => {
            const speaker = item.speaker === 'user' ? '小朋友' : 'AI助手';
            return `【${speaker}】\n${item.content}\n`;
        }).join('\n');
        
        return title + stats + content;
    }
    
    // 复制到剪贴板
    copyToClipboard(text) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        
        this.showMessage('成功', '故事已复制到剪贴板！');
    }
    
    // 获取保存的故事列表
    getSavedStoriesList() {
        const savedStories = JSON.parse(localStorage.getItem('storyChain_saved') || '{}');
        return Object.keys(savedStories).map(title => ({
            title: title,
            turnCount: savedStories[title].turnCount,
            savedAt: savedStories[title].savedAt
        }));
    }
    
    // 更新统计信息
    updateStats() {
        this.storyLengthEl.textContent = this.getTotalWordCount();
        this.turnCountEl.textContent = this.turnCount;
    }
    
    // 获取总字数
    getTotalWordCount() {
        return this.story.reduce((count, item) => count + item.content.length, 0);
    }
    
    // 开始计时器
    startTimer() {
        if (!this.startTime) {
            this.startTime = new Date().toISOString();
        }
        
        setInterval(() => {
            this.timeElapsedEl.textContent = this.getElapsedTime();
        }, 1000);
    }
    
    // 获取已用时间
    getElapsedTime() {
        if (!this.startTime) return '0:00';
        
        const start = new Date(this.startTime);
        const now = new Date();
        const diff = Math.floor((now - start) / 1000);
        
        const minutes = Math.floor(diff / 60);
        const seconds = diff % 60;
        
        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    }
    
    // 显示模态框
    showModal(title, content) {
        this.modalTitle.textContent = title;
        this.modalBody.innerHTML = content;
        this.modal.classList.add('show');
    }
    
    // 隐藏模态框
    hideModal() {
        this.modal.classList.remove('show');
    }
    
    // 显示消息
    showMessage(title, message) {
        this.showModal(title, `<p>${message}</p>`);
    }
    
    // HTML转义
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    // 延迟函数
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// 成语接龙生成器类
class IdiomChain {
    constructor(achievementsSystem = null) {
        this.idiomChain = [];
        this.currentTurn = 'user';
        this.turnCount = 0;
        this.startTime = null;
        this.isGenerating = false;
        this.storyParts = [];
        this.achievementsSystem = achievementsSystem;
        
        // 初始化成语数据库
        this.database = new IdiomDatabase();
        this.validator = new IdiomValidator(this.database);
        
        // 故事生成配置
        this.storyConfig = {
            maxStoryLength: 150,
            creativeThemes: [
                "英雄冒险", "魔法奇幻", "科幻探索", "古代传说", 
                "动物世界", "校园生活", "家庭温情", "友谊故事"
            ]
        };
        
        this.initializeIdiomElements();
        this.bindIdiomEvents();
        this.loadIdiomFromStorage();
        this.startIdiomTimer();
    }
    
    // 初始化成语相关元素
    initializeIdiomElements() {
        // 成语输入元素
        this.idiomInput = document.getElementById('idiomInput');
        this.continueIdiomInput = document.getElementById('continueIdiomInput');
        
        // 成语按钮元素
        this.searchIdiomBtn = document.getElementById('searchIdiomBtn');
        this.startIdiomBtn = document.getElementById('startIdiomBtn');
        this.regenerateIdiomBtn = document.getElementById('regenerateIdiomBtn');
        this.continueIdiomBtn = document.getElementById('continueIdiomBtn');
        this.submitIdiomBtn = document.getElementById('submitIdiomBtn');
        
        // 成语显示元素
        this.idiomChainContainer = document.getElementById('idiomChainContainer');
        this.idiomInputSection = document.getElementById('idiomInputSection');
        this.idiomInfoSection = document.getElementById('idiomInfoSection');
        this.idiomAiResponseSection = document.getElementById('idiomAiResponseSection');
        this.continueIdiomSection = document.getElementById('continueIdiomSection');
        
        // 成语信息元素
        this.currentIdiom = document.getElementById('currentIdiom');
        this.idiomPinyin = document.getElementById('idiomPinyin');
        this.idiomMeaning = document.getElementById('idiomMeaning');
        this.idiomExample = document.getElementById('idiomExample');
        this.idiomStory = document.getElementById('idiomStory');
        
        // AI响应元素
        this.idiomThinkingIndicator = document.getElementById('idiomThinkingIndicator');
        this.idiomAiResponse = document.getElementById('idiomAiResponse');
        this.nextIdiomText = document.getElementById('nextIdiomText');
        this.nextIdiomPinyin = document.getElementById('nextIdiomPinyin');
        this.idiomStoryContent = document.getElementById('idiomStoryContent');
        
        // 提示和统计元素
        this.idiomHintDisplay = document.getElementById('idiomHintDisplay');
        this.requiredChar = document.getElementById('requiredChar');
        this.suggestionList = document.getElementById('suggestionList');
        
        // 统计元素
        this.idiomCount = document.getElementById('idiomCount');
        this.idiomTurnCount = document.getElementById('idiomTurnCount');
        this.learnedIdioms = document.getElementById('learnedIdioms');
        this.idiomTimeElapsed = document.getElementById('idiomTimeElapsed');
    }
    
    // 绑定成语相关事件
    bindIdiomEvents() {
        // 成语输入事件
        this.idiomInput.addEventListener('input', () => this.handleIdiomInput());
        this.continueIdiomInput.addEventListener('input', () => this.handleContinueIdiomInput());
        
        // 成语按钮事件
        this.searchIdiomBtn.addEventListener('click', () => this.searchIdiom());
        this.startIdiomBtn.addEventListener('click', () => this.startIdiomChain());
        this.regenerateIdiomBtn.addEventListener('click', () => this.regenerateIdiomResponse());
        this.continueIdiomBtn.addEventListener('click', () => this.showContinueIdiomInput());
        this.submitIdiomBtn.addEventListener('click', () => this.submitIdiomContinue());
        
        // 回车键支持
        this.idiomInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !this.startIdiomBtn.disabled) {
                this.startIdiomChain();
            }
        });
        
        this.continueIdiomInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !this.submitIdiomBtn.disabled) {
                this.submitIdiomContinue();
            }
        });
    }
    
    // 处理成语输入
    handleIdiomInput() {
        const input = this.idiomInput.value.trim();
        const validation = this.validator.validateInput(input);
        
        this.startIdiomBtn.disabled = !validation.isValid;
        
        // 更新输入样式
        this.idiomInput.classList.remove('valid', 'invalid');
        if (input.length > 0) {
            if (validation.isValid) {
                this.idiomInput.classList.add('valid');
            } else {
                this.idiomInput.classList.add('invalid');
            }
        }
    }
    
    // 处理继续成语输入
    handleContinueIdiomInput() {
        const input = this.continueIdiomInput.value.trim();
        const prevIdiom = this.idiomChain[this.idiomChain.length - 1]?.idiom;
        const validation = this.validator.validateInput(input, prevIdiom);
        
        this.submitIdiomBtn.disabled = !validation.isValid;
        
        // 更新输入样式
        this.continueIdiomInput.classList.remove('valid', 'invalid');
        if (input.length > 0) {
            if (validation.isValid) {
                this.continueIdiomInput.classList.add('valid');
            } else {
                this.continueIdiomInput.classList.add('invalid');
            }
        }
        
        // 更新建议
        if (validation.suggestions.length > 0) {
            this.updateSuggestions(validation.suggestions);
        } else {
            this.suggestionList.innerHTML = '';
        }
    }
    
    // 搜索成语
    searchIdiom() {
        const input = this.idiomInput.value.trim();
        if (!input) return;
        
        const idiomInfo = this.database.searchIdiom(input);
        if (idiomInfo) {
            this.displayIdiomInfo(idiomInfo);
        } else {
            this.showMessage('成语查询', `没有找到"${input}"这个成语，请检查输入是否正确。`);
        }
    }
    
    // 开始成语接龙
    startIdiomChain() {
        const input = this.idiomInput.value.trim();
        const idiomInfo = this.database.searchIdiom(input);
        
        if (!idiomInfo) {
            this.showMessage('提示', '请输入一个有效的成语开始接龙！');
            return;
        }
        
        // 添加到接龙链
        this.addToIdiomChain('user', idiomInfo, '');
        this.currentTurn = 'ai';
        this.turnCount++;
        
        // 更新成就系统
        if (this.achievementsSystem) {
            const newUnlocks = this.achievementsSystem.updateStats('idiom_learned', 1);
            if (newUnlocks.length > 0) {
                setTimeout(() => {
                    newUnlocks.forEach(achievement => {
                        this.achievementsSystem.showAchievementNotification(achievement);
                    });
                }, 1000);
            }
        }
        
        // 更新界面
        this.idiomInputSection.style.display = 'none';
        this.displayIdiomInfo(idiomInfo);
        this.showIdiomThinking();
        
        // 生成AI响应
        setTimeout(() => {
            this.generateIdiomResponse(input);
        }, 1000);
        
        // 更新统计
        this.updateIdiomStats();
    }
    
    // 添加到成语接龙链
    addToIdiomChain(speaker, idiomInfo, storyPart) {
        this.idiomChain.push({
            speaker: speaker,
            idiom: idiomInfo.idiom,
            pinyin: idiomInfo.pinyin,
            meaning: idiomInfo.meaning,
            example: idiomInfo.example,
            story: idiomInfo.story,
            storyPart: storyPart,
            timestamp: new Date().toISOString()
        });
        
        if (storyPart) {
            this.storyParts.push(storyPart);
        }
        
        this.renderIdiomChain();
        this.saveIdiomToStorage();
    }
    
    // 渲染成语接龙链
    renderIdiomChain() {
        if (this.idiomChain.length === 0) {
            this.idiomChainContainer.innerHTML = `
                <div class="idiom-placeholder">
                    <div class="idiom-wand">🏮</div>
                    <h2>开始成语接龙故事</h2>
                    <p>输入一个成语开始，我们将围绕这些成语创作精彩的故事！</p>
                </div>
            `;
            return;
        }
        
        const chainHTML = this.idiomChain.map((item, index) => {
            const speakerClass = item.speaker === 'user' ? 'user' : 'ai';
            const speakerIcon = item.speaker === 'user' ? '👶' : '🤖';
            const speakerLabel = item.speaker === 'user' ? '小朋友' : 'AI助手';
            
            return `
                <div class="idiom-item ${speakerClass}">
                    <div class="idiom-item-header">
                        <div>
                            <span class="speaker-icon">${speakerIcon}</span>
                            <span class="idiom-text">${item.idiom}</span>
                            <span class="idiom-pinyin">${item.pinyin}</span>
                        </div>
                        <span class="idiom-number">第${index + 1}个</span>
                    </div>
                    ${item.storyPart ? `<div class="idiom-story-content">${item.storyPart}</div>` : ''}
                </div>
            `;
        }).join('');
        
        this.idiomChainContainer.innerHTML = `
            <div class="idiom-chain">
                ${chainHTML}
            </div>
        `;
        
        // 滚动到最新内容
        this.idiomChainContainer.scrollTop = this.idiomChainContainer.scrollHeight;
    }
    
    // 显示成语信息
    displayIdiomInfo(idiomInfo) {
        this.currentIdiom.textContent = idiomInfo.idiom;
        this.idiomPinyin.textContent = idiomInfo.pinyin;
        this.idiomMeaning.textContent = idiomInfo.meaning;
        this.idiomExample.textContent = idiomInfo.example;
        this.idiomStory.textContent = idiomInfo.story;
        
        this.idiomInfoSection.style.display = 'block';
    }
    
    // 显示成语思考指示器
    showIdiomThinking() {
        this.idiomThinkingIndicator.style.display = 'flex';
        this.idiomAiResponse.style.display = 'none';
        this.isGenerating = true;
    }
    
    // 隐藏成语思考指示器
    hideIdiomThinking() {
        this.idiomThinkingIndicator.style.display = 'none';
        this.idiomAiResponse.style.display = 'block';
        this.isGenerating = false;
    }
    
    // 生成成语AI响应
    generateIdiomResponse(prevIdiom) {
        // 获取下一个成语
        const lastChar = prevIdiom[prevIdiom.length - 1];
        const nextIdioms = this.database.findNextIdioms(lastChar);
        
        if (nextIdioms.length === 0) {
            this.showMessage('提示', `没有找到以"${lastChar}"字开头的成语，换个成语试试吧！`);
            this.hideIdiomThinking();
            return;
        }
        
        // 随机选择一个成语
        const nextIdiom = nextIdioms[Math.floor(Math.random() * nextIdioms.length)];
        
        // 生成故事片段
        const storyPart = this.generateStoryFragment(prevIdiom, nextIdiom.idiom);
        
        // 添加到接龙链
        this.addToIdiomChain('ai', nextIdiom, storyPart);
        this.turnCount++;
        
        // 显示响应
        this.nextIdiomText.textContent = nextIdiom.idiom;
        this.nextIdiomPinyin.textContent = nextIdiom.pinyin;
        this.idiomStoryContent.textContent = storyPart;
        this.hideIdiomThinking();
        
        // 更新统计
        this.updateIdiomStats();
    }
    
    // 生成故事片段
    generateStoryFragment(prevIdiom, currentIdiom) {
        const templates = [
            `就在这时，${prevIdiom}的情景发生了意想不到的变化，${currentIdiom}，整个故事变得更加精彩了！`,
            `正当大家以为${prevIdiom}就是结局时，突然${currentIdiom}，一个新的篇章开始了！`,
            `经历了${prevIdiom}的事件后，主人公发现${currentIdiom}，这让他的人生轨迹发生了改变。`,
            `从${prevIdiom}到${currentIdiom}，故事的转折让人猝不及防，接下来会发生什么呢？`,
            `${prevIdiom}还历历在目，却又${currentIdiom}，真是一波未平一波又起！`
        ];
        
        return templates[Math.floor(Math.random() * templates.length)];
    }
    
    // 重新生成成语响应
    regenerateIdiomResponse() {
        if (this.isGenerating || this.idiomChain.length === 0) return;
        
        // 移除最后一个AI响应
        if (this.idiomChain.length > 0 && this.idiomChain[this.idiomChain.length - 1].speaker === 'ai') {
            this.idiomChain.pop();
            this.storyParts.pop();
        }
        
        const lastUserItem = this.idiomChain.filter(item => item.speaker === 'user').pop();
        if (lastUserItem) {
            this.renderIdiomChain();
            this.showIdiomThinking();
            setTimeout(() => {
                this.generateIdiomResponse(lastUserItem.idiom);
            }, 1000);
        }
    }
    
    // 显示继续成语输入
    showContinueIdiomInput() {
        this.idiomAiResponseSection.style.display = 'none';
        this.continueIdiomSection.style.display = 'block';
        this.currentTurn = 'user';
        
        // 设置提示
        const lastIdiom = this.idiomChain[this.idiomChain.length - 1].idiom;
        const requiredChar = lastIdiom[lastIdiom.length - 1];
        this.requiredChar.textContent = requiredChar;
        
        // 提供建议
        const suggestions = this.database.getSuggestions(requiredChar, 3);
        this.updateSuggestions(suggestions);
        
        this.continueIdiomInput.focus();
    }
    
    // 提交成语继续
    submitIdiomContinue() {
        const input = this.continueIdiomInput.value.trim();
        const prevIdiom = this.idiomChain[this.idiomChain.length - 1].idiom;
        
        if (!this.validator.isValidChain(prevIdiom, input)) {
            this.showMessage('提示', this.validator.getErrorMessage(input, prevIdiom));
            return;
        }
        
        const idiomInfo = this.database.searchIdiom(input);
        
        // 添加到接龙链
        this.addToIdiomChain('user', idiomInfo, '');
        this.turnCount++;
        
        // 清空输入
        this.continueIdiomInput.value = '';
        this.submitIdiomBtn.disabled = true;
        
        // 切换到AI响应
        this.currentTurn = 'ai';
        this.continueIdiomSection.style.display = 'none';
        this.idiomAiResponseSection.style.display = 'block';
        this.showIdiomThinking();
        
        // 生成AI响应
        setTimeout(() => {
            this.generateIdiomResponse(input);
        }, 1000);
        
        // 更新统计
        this.updateIdiomStats();
    }
    
    // 更新建议列表
    updateSuggestions(suggestions) {
        this.suggestionList.innerHTML = suggestions.map(idiom => 
            `<span class="suggestion-item" data-idiom="${idiom.idiom}">${idiom.idiom}</span>`
        ).join('');
        
        // 添加点击事件
        this.suggestionList.querySelectorAll('.suggestion-item').forEach(item => {
            item.addEventListener('click', () => {
                const idiom = item.dataset.idiom;
                this.continueIdiomInput.value = idiom;
                this.handleContinueIdiomInput();
            });
        });
    }
    
    // 更新成语统计
    updateIdiomStats() {
        this.idiomCount.textContent = this.idiomChain.length;
        this.idiomTurnCount.textContent = this.turnCount;
        
        // 计算学会的成语数量（去重）
        const learnedIdiomsSet = new Set(this.idiomChain.map(item => item.idiom));
        this.learnedIdioms.textContent = learnedIdiomsSet.size;
    }
    
    // 开始成语计时器
    startIdiomTimer() {
        if (!this.startTime) {
            this.startTime = new Date().toISOString();
        }
        
        setInterval(() => {
            this.idiomTimeElapsed.textContent = this.getElapsedTime();
        }, 1000);
    }
    
    // 获取已用时间
    getElapsedTime() {
        if (!this.startTime) return '0:00';
        
        const start = new Date(this.startTime);
        const now = new Date();
        const diff = Math.floor((now - start) / 1000);
        
        const minutes = Math.floor(diff / 60);
        const seconds = diff % 60;
        
        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    }
    
    // 保存到本地存储
    saveIdiomToStorage() {
        const data = {
            idiomChain: this.idiomChain,
            storyParts: this.storyParts,
            turnCount: this.turnCount,
            startTime: this.startTime,
            lastSaved: new Date().toISOString()
        };
        
        localStorage.setItem('idiomChain_current', JSON.stringify(data));
    }
    
    // 从本地存储加载
    loadIdiomFromStorage() {
        const savedData = localStorage.getItem('idiomChain_current');
        if (savedData) {
            try {
                const data = JSON.parse(savedData);
                this.idiomChain = data.idiomChain || [];
                this.storyParts = data.storyParts || [];
                this.turnCount = data.turnCount || 0;
                this.startTime = data.startTime;
                
                if (this.idiomChain.length > 0) {
                    this.renderIdiomChain();
                    this.updateIdiomStats();
                    
                    // 显示适当的界面
                    this.idiomInputSection.style.display = 'none';
                    if (this.idiomChain[this.idiomChain.length - 1].speaker === 'ai') {
                        this.showContinueIdiomInput();
                    } else {
                        this.idiomInfoSection.style.display = 'block';
                        if (this.idiomChain.length > 1) {
                            this.idiomAiResponseSection.style.display = 'block';
                            this.hideIdiomThinking();
                        }
                    }
                }
            } catch (error) {
                console.error('加载成语接龙数据失败:', error);
            }
        }
    }
    
    // 显示消息
    showMessage(title, message) {
        if (window.storyChain) {
            window.storyChain.showMessage(title, message);
        }
    }
}

// 成就界面管理器
class AchievementsManager {
    constructor(achievementsSystem) {
        this.achievements = achievementsSystem;
        this.initializeElements();
        this.bindEvents();
    }
    
    // 初始化元素
    initializeElements() {
        this.achievementsBtn = document.getElementById('achievementsBtn');
        this.achievementsModal = document.getElementById('achievementsModal');
        this.achievementCategories = document.querySelectorAll('.achievement-category');
        this.achievementsGrid = document.getElementById('achievementsGrid');
        this.unlockedCount = document.getElementById('unlockedCount');
        this.totalCount = document.getElementById('totalCount');
        this.achievementProgress = document.getElementById('achievementProgress');
    }
    
    // 绑定事件
    bindEvents() {
        if (this.achievementsBtn) {
            this.achievementsBtn.addEventListener('click', () => this.showAchievementsModal());
        }
        
        this.achievementCategories.forEach(category => {
            category.addEventListener('click', () => {
                const targetCategory = category.dataset.category;
                this.switchAchievementCategory(targetCategory);
            });
        });
        
        // 关闭按钮
        document.querySelectorAll('.achievements-modal-close').forEach(btn => {
            btn.addEventListener('click', () => this.hideAchievementsModal());
        });
        
        // 点击背景关闭
        if (this.achievementsModal) {
            this.achievementsModal.addEventListener('click', (e) => {
                if (e.target === this.achievementsModal) {
                    this.hideAchievementsModal();
                }
            });
        }
    }
    
    // 显示成就模态框
    showAchievementsModal() {
        this.updateAchievementsDisplay('all');
        this.achievementsModal.classList.add('show');
    }
    
    // 隐藏成就模态框
    hideAchievementsModal() {
        this.achievementsModal.classList.remove('show');
    }
    
    // 切换成就分类
    switchAchievementCategory(category) {
        this.achievementCategories.forEach(cat => {
            cat.classList.remove('active');
            if (cat.dataset.category === category) {
                cat.classList.add('active');
            }
        });
        
        this.updateAchievementsDisplay(category);
    }
    
    // 更新成就显示
    updateAchievementsDisplay(category) {
        const achievements = this.achievements.getAchievements();
        const unlockedAchievements = this.achievements.getUnlockedAchievements();
        const stats = this.achievements.getStats();
        
        let filteredAchievements = Object.values(achievements);
        
        if (category !== 'all') {
            filteredAchievements = filteredAchievements.filter(achievement => 
                achievement.category === category
            );
        }
        
        let html = '';
        filteredAchievements.forEach(achievement => {
            const isUnlocked = unlockedAchievements.includes(achievement.id);
            let progress = '';
            
            if (!isUnlocked) {
                const progressData = this.getAchievementProgress(achievement.id, stats);
                progress = `
                    <div class="achievement-progress">
                        进度: ${progressData.current}/${progressData.target} (${progressData.percentage}%)
                    </div>
                `;
            } else {
                const unlockDate = this.getAchievementUnlockDate(achievement.id);
                progress = `<div class="achievement-date">${unlockDate}</div>`;
            }
            
            html += `
                <div class="achievement-card ${isUnlocked ? 'unlocked' : ''}">
                    <div class="achievement-icon">${achievement.icon}</div>
                    <div class="achievement-title">${achievement.title}</div>
                    <div class="achievement-description">${achievement.description}</div>
                    ${progress}
                </div>
            `;
        });
        
        this.achievementsGrid.innerHTML = html;
        
        // 更新统计信息
        const totalUnlocked = unlockedAchievements.length;
        const totalAchievements = Object.keys(achievements).length;
        const progressPercent = Math.round((totalUnlocked / totalAchievements) * 100);
        
        if (this.unlockedCount) this.unlockedCount.textContent = totalUnlocked;
        if (this.totalCount) this.totalCount.textContent = totalAchievements;
        if (this.achievementProgress) this.achievementProgress.textContent = `${progressPercent}%`;
    }
    
    // 获取成就进度
    getAchievementProgress(achievementId, stats) {
        const achievement = this.achievements.achievements[achievementId];
        if (!achievement) return { current: 0, target: 0, percentage: 0 };
        
        const condition = achievement.condition;
        let currentValue = 0;
        
        switch (condition.type) {
            case 'story_count':
                currentValue = stats.storyCount;
                break;
            case 'total_words':
                currentValue = stats.totalWords;
                break;
            case 'single_story_words':
                currentValue = stats.maxStoryWords;
                break;
            case 'idiom_count':
                currentValue = stats.idiomCount;
                break;
            case 'chain_length':
                currentValue = stats.maxChainLength;
                break;
            case 'study_days':
                currentValue = stats.studyDays;
                break;
            case 'streak_days':
                currentValue = stats.currentStreak;
                break;
            case 'total_xp':
                currentValue = stats.totalXP;
                break;
            default:
                currentValue = 0;
        }
        
        const target = condition.value;
        const percentage = Math.min(100, Math.round((currentValue / target) * 100));
        
        return { current: currentValue, target, percentage };
    }
    
    // 获取成就解锁日期
    getAchievementUnlockDate(achievementId) {
        // 这里可以从存储中获取具体的解锁日期
        // 简化实现，返回最近日期
        return new Date().toLocaleDateString();
    }
}

// 模式切换管理器
class ModeManager {
    constructor() {
        this.currentMode = 'story';
        this.storyChain = null;
        this.idiomChain = null;
        this.achievementsSystem = null;
        this.statsManager = null;
        this.achievementsManager = null;
        
        this.initializeModeElements();
        this.bindModeEvents();
    }
    
    // 初始化模式元素
    initializeModeElements() {
        this.storyModeTab = document.getElementById('storyModeTab');
        this.idiomModeTab = document.getElementById('idiomModeTab');
        this.storyMode = document.getElementById('storyMode');
        this.idiomMode = document.getElementById('idiomMode');
        this.storyStats = document.getElementById('storyStats');
        this.idiomStats = document.getElementById('idiomStats');
    }
    
    // 绑定模式事件
    bindModeEvents() {
        this.storyModeTab.addEventListener('click', () => this.switchMode('story'));
        this.idiomModeTab.addEventListener('click', () => this.switchMode('idiom'));
    }
    
    // 切换模式
    switchMode(mode) {
        if (this.currentMode === mode) return;
        
        // 更新标签状态
        document.querySelectorAll('.mode-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        
        if (mode === 'story') {
            this.storyModeTab.classList.add('active');
            this.storyMode.style.display = 'block';
            this.idiomMode.style.display = 'none';
            this.storyStats.style.display = 'grid';
            this.idiomStats.style.display = 'none';
        } else {
            this.idiomModeTab.classList.add('active');
            this.storyMode.style.display = 'none';
            this.idiomMode.style.display = 'block';
            this.storyStats.style.display = 'none';
            this.idiomStats.style.display = 'grid';
        }
        
        this.currentMode = mode;
        
        // 保存当前模式到存储
        localStorage.setItem('currentMode', mode);
    }
    
    // 初始化应用
    initialize() {
        // 初始化成就系统
        this.achievementsSystem = new AchievementsSystem();
        
        // 初始化两个应用
        this.storyChain = new StoryChain(this.achievementsSystem);
        this.idiomChain = new IdiomChain(this.achievementsSystem);
        
        // 初始化管理器
        this.statsManager = new StatsManager(this.achievementsSystem);
        this.achievementsManager = new AchievementsManager(this.achievementsSystem);
        
        // 每日登录奖励
        this.checkDailyLogin();
        
        // 恢复上次使用的模式
        const savedMode = localStorage.getItem('currentMode') || 'story';
        this.switchMode(savedMode);
    }
    
    // 检查每日登录
    checkDailyLogin() {
        const today = new Date().toDateString();
        const lastLogin = localStorage.getItem('last_login_date');
        
        if (lastLogin !== today) {
            // 新的一天，给登录奖励
            const newUnlocks = this.achievementsSystem.updateStats('daily_login', 1);
            
            // 显示成就解锁通知
            if (newUnlocks.length > 0) {
                setTimeout(() => {
                    newUnlocks.forEach(achievement => {
                        this.achievementsSystem.showAchievementNotification(achievement);
                    });
                }, 1000);
            }
            
            localStorage.setItem('last_login_date', today);
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 添加加载动画
    document.body.style.opacity = '0';
    setTimeout(() => {
        document.body.style.transition = 'opacity 0.5s ease';
        document.body.style.opacity = '1';
    }, 100);
    
    // 初始化模式管理器
    window.modeManager = new ModeManager();
    window.modeManager.initialize();
    
    // 添加页面可见性变化监听
    document.addEventListener('visibilitychange', () => {
        if (!document.hidden) {
            if (window.modeManager.storyChain) {
                window.modeManager.storyChain.saveToStorage();
            }
            if (window.modeManager.idiomChain) {
                window.modeManager.idiomChain.saveIdiomToStorage();
            }
        }
    });
    
    // 添加页面离开前保存
    window.addEventListener('beforeunload', () => {
        if (window.modeManager.storyChain) {
            window.modeManager.storyChain.saveToStorage();
        }
        if (window.modeManager.idiomChain) {
            window.modeManager.idiomChain.saveIdiomToStorage();
        }
    });
});

// 添加故事段的样式
const additionalStyles = `
<style>
.story-segment {
    margin-bottom: 20px;
    padding: 20px;
    border-radius: 12px;
    animation: fadeInUp 0.5s ease;
}

.user-part {
    background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
    border-left: 4px solid #0ea5e9;
}

.ai-part {
    background: linear-gradient(135deg, #f3e8ff 0%, #e9d5ff 100%);
    border-left: 4px solid #9333ea;
}

.segment-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 12px;
    font-weight: 600;
}

.speaker-icon {
    font-size: 1.5rem;
}

.speaker-label {
    color: var(--text-primary);
}

.segment-number {
    margin-left: auto;
    background: var(--bg-tertiary);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.9rem;
    color: var(--text-secondary);
}

.segment-content {
    line-height: 1.8;
    font-size: 1.1rem;
}

.story-selector {
    padding: 20px 0;
}

.story-select {
    width: 100%;
    padding: 12px;
    border: 2px solid var(--border-color);
    border-radius: var(--border-radius);
    font-size: 1rem;
    margin: 15px 0;
}

.story-actions {
    display: flex;
    gap: 15px;
    justify-content: flex-end;
}

.btn-danger {
    background: var(--error-color);
    color: white;
}

.btn-danger:hover {
    background: #dc2626;
}
</style>
`;

// 将额外样式添加到页面
document.head.insertAdjacentHTML('beforeend', additionalStyles);